package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.mapper.CheckGroupMapper;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * <h3>health94_pareant</h3>
 * <p></p>
 *
 * @author : hhw
 * @date : 2020-03-18 22:31
 **/



@Service(interfaceClass = CheckGroupService.class)
public class CheckGroupServiceImpl implements CheckGroupService {
    /*
    * 用于新增检查组
    *
    * */
    @Autowired
    private CheckGroupMapper checkGroupMapper;

    @Override
    public void add(Integer[] checkitems, CheckGroup checkGroup) {

        //先将checkGroup内容添加进group数据库
        checkGroupMapper.add(checkGroup);

        //将检查组和检查项组合起来
       checkGroupRelateCheckItem(checkitems, checkGroup.getId());
    }


    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {

        PageHelper.startPage(currentPage, pageSize);

        //使用分页插件后只需要按条件查询即可
        List<CheckGroup> list = checkGroupMapper.findPage(queryString);

        PageInfo<CheckGroup> checkGroupPageInfo = new PageInfo<>(list);

        return new PageResult(checkGroupPageInfo.getTotal(), checkGroupPageInfo.getList());

    }

    @Override
    public void deleteById(Integer id) {
        //先查找是否有关联套餐的
        int count = checkGroupMapper.findCheckGroupRelateSetmeal(id);

        if (count != 0) {
            throw new RuntimeException(MessageConstant.CHECKGROUP_IS_QUOTED);
        } else {
            //删除检查组和检查项的关联
            checkGroupMapper.deleteCheckItemRelateCheckGroup(id);

            checkGroupMapper.deleteById(id);
        }
    }

    @Override
    public List<Integer> queryCheckItemsByCheckGroupId(Integer id) {

        return checkGroupMapper.queryCheckItemsByCheckGroupId(id);

    }


    @Override
    public void edit(Integer[] checkitems, CheckGroup checkGroup) {

        checkGroupMapper.edit(checkGroup);

        //删除原检查组与检查项的关联
        checkGroupMapper.deleteCheckItemRelateCheckGroup(checkGroup.getId());

        //添加关联
        checkGroupRelateCheckItem(checkitems, checkGroup.getId());

    }
    //用于删除检查项和检查组的关联关系
    private void checkGroupRelateCheckItem(Integer[] checkitems, Integer id) {

        checkGroupMapper.relate(checkitems, id);

    }
}
